import car from "./carousel.js"
import superHero from "./superhero.js"
import searchTrailer from "./searchTrailer.js"

let Mock = {
	timeout: "1000-3000",
	// 存放拦截到的接口数组
	intercepts: [],
	// 拦截接口的方法，regex:拦截的正则接口 method:请求的方式 response：请求返回的数据
	mock: (regex, method, response) => {
		// 存放在数组中
		Mock.intercepts.push({
			regex: regex,
			method: method,
			response: response
		})
	},
	response: config => {
		return new Promise((resolve, reject) => {
			// 模仿网络请求所需的时间
			const dey = Math.floor(Math.random() * Mock.timeout.split('-')[0] + Mock.timeout.split('-')[1]);
			setTimeout(function() {
				// 是否启用mock
				let match = false;
				let findIntercept = null;
				for (let index in Mock.intercepts) {
					let intercept = Mock.intercepts[index];
					if (intercept.regex==config.url && config.method == intercept.method) {
						match = true;
						findIntercept = intercept;
					}
				}
				if (match) {
					resolve({
						statusCode: "200",
						data: findIntercept.response(config)
					})
				} else {
					reject(`未找到对应${config.method} ${config.url}的模拟响应`);
				}
			}, dey)
		})
	}
}

Mock.mock("/superhero/index/carousel/list?qq=lee49586454", "POST", car.carousel);
Mock.mock("/superhero/index/movie/hot?type=superhero&qq=lee49586454", "POST", superHero.superHero);
Mock.mock("/superhero/searchtrailer", "POST", searchTrailer.searchTrailer); 

export default Mock;
